package com.yz.admin.service;

import com.yz.admin.dao.UserDao;
import com.yz.admin.mapper.AdminMapper;
import com.yz.admin.mapper.LogMapper;
import com.yz.admin.pojo.User;
import com.yz.admin.vo.SubmitVo;
import com.yz.common.pojo.DbLink;
import com.yz.common.pojo.DbType;
import com.yz.common.pojo.LogSheet;
import com.yz.common.pojo.Task;
import com.yz.common.utils.JdbcUtils;
import com.yz.common.utils.Result;
import com.yz.common.utils.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.sql.SQLException;
import java.util.*;

@Service
public class AdminService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private AdminMapper adminMapper;


    //查询所有用户
    public List<User> findAllUser(String status) {
        return adminMapper.findAllUser(status);
    }

    //删除用户(假删除)
    public int deleteUserById(Integer id,String status) {
        return adminMapper.deleteUserById(id,status);
    }


    //修改用户权限
    @Transactional
    public Result updateUser(User user) {

        Map map=adminMapper.findbyRole(user.getRoleid());
        String roles = (String) map.get("roleName");
        if(roles.equals("ADMIN")){
            return new Result(false, StatusCode.ERROR,"无权限","修改"+user.getUsername()+"的权限为:"+roles);
        }
        user.setRoles(roles);
        adminMapper.updateUser(user);
        return new Result(true, StatusCode.OK,"修改成功","修改"+user.getUsername()+"的权限为:"+roles);
    }

    //查看任务列表
    public List<Task> findAllTask() {
        return adminMapper.findAllTask();
    }

    //审核任务
    public int updateTaskStatus(SubmitVo submitVo) {
        Integer userId = adminMapper.findUserIdByUsername(submitVo.getUsername());
        submitVo.setPdate(new Date());
        submitVo.setUserId(userId);
        return adminMapper.updateTaskStatus(submitVo);
    }

    //添加数据库连接
    @Transactional
    public Result addDatabaseLink(DbLink dbLink) {
        try {
            String dbTypeName = adminMapper.getDbTypeNameByDbTypeId(dbLink.getDbType());
            dbLink.setDbTypeName(dbTypeName);
            if(dbLink.getDbType() == 1){
                //==1为mysql
                dbLink.setDriver("com.mysql.jdbc.Driver");
            }
            adminMapper.addDatabaseLink(dbLink);

            Map map = getMapByDbLink(dbLink, dbLink.getUsername(), dbLink.getPassword());
            ArrayList<String> databasesArray = new ArrayList<>();
            List<Map> databases = JdbcUtils.queryData(map, "SHOW DATABASES");

            for (Map database : databases) {

                String[] split = database.toString().split("=");

                databasesArray.add(split[1].substring(0,split[1].length()-1));
            }
            for (String databasesName : databasesArray) {
                adminMapper.insertDatabase(dbLink.getId(),dbLink.getUsername(),dbLink.getPassword(),databasesName);
            }
        } catch (SQLException e) {
            return new Result(false, StatusCode.ERROR,"出现异常");
        }
        return null;
    }
    //获取基本四项map
    public Map getMapByDbLink(DbLink dbLink,String username,String password){
        StringBuffer url = new StringBuffer();
        // ==1 说明是mysql
        if(dbLink.getDbType() == 1){
            url.append("jdbc:mysql://");
            url.append(dbLink.getIp());
            url.append(":");
            url.append(dbLink.getPort());
            url.append("/mysql?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=UTC");
        }

        Map map=new HashMap();
        map.put("driver", dbLink.getDriver());
        map.put("url", url.toString());
        map.put("username", username);
        map.put("pass", password);

        return map;
    }

    //查询数据库连接
    public DbLink findLinkById(Integer linkId) {
        return adminMapper.findLinkById(linkId);
    }

    //添加数据库
    public void insertDatabase(Integer linkId, String username, String password, String databasesName) {
        adminMapper.insertDatabase(linkId,username,password,databasesName);
    }

    //删除数据库连接
    @Transactional
    public int deleteDbLinkById(Integer linkId) {
        int i = adminMapper.deleteDbLinkById(linkId);
        adminMapper.deleteDatabaseByLinkId(linkId);
        return i;
    }

    public List<DbType> getAllDatabaseType() {
        return adminMapper.getAllDatabaseType();
    }

    public List<DbLink> getAllDbLink() {
        return adminMapper.getAllDbLink();
    }

    @Autowired
    private LogMapper logMapper;
    public void addLog(LogSheet logSheet) {
        logMapper.insertLog(logSheet);
    }

    public List<LogSheet> findAllLog(Integer pageNum, Integer pageSize) {
        Integer pageIndex = (pageNum-1)*pageSize;
        return logMapper.findAllLog(pageIndex,pageSize);
    }

    public Integer findLogCount() {
        return logMapper.findLogCount();
    }
}
